<?php

namespace app\api\controller;

use app\admin\model\shopro\chat\CustomerService;
use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\Announcement;
use app\common\model\Area;
use app\common\model\Group;
use app\common\model\Msg;
use app\common\model\MsgRead;
use app\common\model\MsgType;
use app\common\model\TutoringPriceRules;
use app\common\model\Version;
use fast\Random;
use think\captcha\Captcha;
use think\Config;
use think\Db;
use think\Hook;

/**
 * 公共接口
 */
class Common extends Api
{
    protected $noNeedLogin = ['init', 'captcha', 'getAnnouncementLst', 'getAnnouncementInfo'];
    protected $noNeedRight = '*';

    public function _initialize()
    {

        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header('Access-Control-Expose-Headers: __token__');//跨域让客户端获取到
        }
        //跨域检测
        check_cors_request();

        if (!isset($_COOKIE['PHPSESSID'])) {
            Config::set('session.id', $this->request->server("HTTP_SID"));
        }
        parent::_initialize();
    }

    /**
     * 加载初始化
     *
     * @param string $version 版本号
     * @param string $lng 经度
     * @param string $lat 纬度
     */
    public function init()
    {
        if ($version = $this->request->request('version')) {
            $lng = $this->request->request('lng');
            $lat = $this->request->request('lat');

            //配置信息
            $upload = Config::get('upload');
            //如果非服务端中转模式需要修改为中转
            if ($upload['storage'] != 'local' && isset($upload['uploadmode']) && $upload['uploadmode'] != 'server') {
                //临时修改上传模式为服务端中转
                set_addon_config($upload['storage'], ["uploadmode" => "server"], false);

                $upload = \app\common\model\Config::upload();
                // 上传信息配置后
                Hook::listen("upload_config_init", $upload);

                $upload = Config::set('upload', array_merge(Config::get('upload'), $upload));
            }

            $upload['cdnurl'] = $upload['cdnurl'] ? $upload['cdnurl'] : cdnurl('', true);
            $upload['uploadurl'] = preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $upload['uploadurl']) ? $upload['uploadurl'] : url($upload['storage'] == 'local' ? '/api/common/upload' : $upload['uploadurl'], '', false, true);

            $content = [
                'citydata' => Area::getCityFromLngLat($lng, $lat),
                'versiondata' => Version::check($version),
                'uploaddata' => $upload,
                'coverdata' => Config::get("cover"),
            ];
            $this->success('', $content);
        } else {
            $this->error(__('Invalid parameters'));
        }
    }

    /**
     * 上传文件
     * @ApiMethod (POST)
     * @param File $file 文件流
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            }

            $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        }

    }

    /**
     * 验证码
     * @param $id
     * @return \think\Response
     */
    public function captcha($id = "")
    {
        \think\Config::set([
            'captcha' => array_merge(config('captcha'), [
                'fontSize' => 44,
                'imageH' => 150,
                'imageW' => 350,
            ])
        ]);
        $captcha = new Captcha((array)Config::get('captcha'));
        return $captcha->entry($id);
    }

    /**
     * 公告列表
     * @return void
     * @throws \think\exception\DbException
     */
    public function getAnnouncementLst()
    {
        $page = $this->request->param('page') ?: 1;
        $limit = $this->request->param('limit') ?: 10;
        $list = Announcement::where(['status' => '1'])
            ->order('id', 'desc')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ]);

        $this->success('获取成功！', $list);
    }

    /**
     * 公告详情
     * @return void
     * @throws \think\exception\DbException
     */
    public function getAnnouncementInfo()
    {
        $info = Announcement::get(['id' => $this->request->param('a_id'), 'status' => '1']);
        if (!$info)
            $this->success('获取成功！', []);

        $this->success('获取成功！', $info);
    }

    /**
     * 群组列表
     * @return void
     * @throws \think\exception\DbException
     */
    public function getGroupLst()
    {
        $page = $this->request->param('page') ?: 1;
        $limit = $this->request->param('limit') ?: 10;
        $list = Group::where(['status' => '1'])
            ->order('id', 'desc')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ]);

        $this->success('获取成功！', $list);
    }

    /**
     * 消息列表
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getMsgLst()
    {
        $msg_type_id = $this->request->param('msg_id') ?: 1;
        $list = Msg::where('find_in_set(:uid, user_ids)', ['uid' => $this->auth->id])
            ->where(['type_id' => $msg_type_id])
            ->order('id', 'desc')
            ->select();
        foreach ($list as $k => $v) {
            $list[$k]['friendly_time'] = friendlyDate($v['createtime'], 'mohu');
            $list[$k]['createtime'] = date('Y-m-d H:i:s', $v['createtime']);
            // 查询是否已读
            $list[$k]['is_read'] = MsgRead::get(['msg_id' => $v['id'], 'uid' => $this->auth->id]) ? 1 : 0;
        }
        $this->success('操作成功', $list);
    }

    /**
     * 消息详情
     * @return void
     * @throws \think\exception\DbException
     */
    public function getMsgInfo()
    {
        $msg_id = $this->request->param('msg_id');
        $msgInfo = Msg::get(['id' => $msg_id]);
        if (!$msgInfo)
            $this->error(__('消息数据不存在'));

        $data = ['msg_id' => $msg_id, 'uid' => $this->auth->id];
        $info = MsgRead::get($data);
        if (!$info) {
            MsgRead::create($data);
        }

        $msgInfo['friendly_time'] = friendlyDate($msgInfo['createtime'], 'mohu');
        $msgInfo['createtime'] = date('Y-m-d H:i:s', $msgInfo['createtime']);
        $this->success('操作成功', $msgInfo);
    }

    public function getOrderTime()
    {
        $order_id = $this->request->param('order_id');
        $orderInfo = Db::table('jy_shopro_order')->where(['id' => $order_id])->find();
        if (!$orderInfo){
            $this->error(__('订单数据不存在'));
        }
        if($orderInfo['status'] == 'completed'){
            $this->error(__('时长已到期'));
        }
        $this->success('操作成功', $orderInfo);
    }


    /**
     * 获取主页消息
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getHomeMsg()
    {
        $list = MsgType::select();
        foreach ($list as $k => $v) {
            $columnId = Msg::where('find_in_set(:uid, user_ids)', ['uid' => $this->auth->id])->where(['type_id' => $v['id']])->order('id', 'desc')->column('id');
            $list[$k]['is_new_msg'] = 0;
            $list[$k]['friendly_time'] = $list[$k]['title'] = '';
            if ($columnId) {
                // 获取已读id
                $readIdArr = MsgRead::whereIn('msg_id', $columnId)->where(['uid' => $this->auth->id])->column('msg_id');
                $diffArr = array_diff($columnId, $readIdArr);
                // 有最新的
                if ($diffArr) {
                    $newestId = array_values($diffArr)[0];
                    $is_new_msg = count($diffArr);
                } else {
                    $newestId = $columnId[0];
                    $is_new_msg = 0;
                }
                $info = Msg::get(['id' => $newestId]);
                $list[$k]['is_new_msg'] = $is_new_msg;
                $list[$k]['title'] = $info['title'];
                $list[$k]['friendly_time'] = friendlyDate($info['createtime'], 'mohu');
            }
        }
        $this->success('操作成功', $list);
    }

    /**
     * 未读消息数
     * @return void
     */
    public function countMsgNums()
    {
        $columnId = Msg::where('find_in_set(:uid, user_ids)', ['uid' => $this->auth->id])->column('id');
        $total = 0;
        if ($columnId) {
            $readIdArr = MsgRead::whereIn('msg_id', $columnId)->where(['uid' => $this->auth->id])->column('msg_id');
            $diffArr = array_diff($columnId, $readIdArr);
            // 有最新的
            if ($diffArr) {
                $total += count($diffArr);
            }
        }
        $this->success('操作成功', $total);
    }

    /**
     * 获取辅导师列表
     * @return void
     * @throws \think\exception\DbException
     */
    public function getAssistantSupervisorLst()
    {
        $page = $this->request->param('page') ?: 1;
        $limit = $this->request->param('limit') ?: 10;
        $list = CustomerService::order('id', 'desc')
//            ->where(['status' => 'online'])
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ]);

        $new_list = [];
        foreach ($list as $kk => $vv) {
            $new_list[$kk]['id'] = $vv['id'];
            $new_list[$kk]['name'] = $vv['name'];
            $new_list[$kk]['avatar'] = cdnurl($vv['avatar'], true);
            $new_list[$kk]['status'] = $vv['status'];
            $new_list[$kk]['createtime'] = $vv['createtime'];
        }

        $this->success('获取成功！', $new_list);
    }

    /**
     * 获取辅导师详情
     * @return void
     * @throws \think\exception\DbException
     */
    public function getAssistantSupervisorInfo()
    {
        $s_id = $this->request->param('s_id');
        $info = CustomerService::get(['id' => $s_id]);
        if (!$info)
            $this->error(__('辅导师数据不存在'));

        $new_info['id'] = $info['id'];
        $new_info['name'] = $info['name'];
        $new_info['avatar'] = cdnurl($info['avatar'], true);
        $new_info['status'] = $info['status'];
        $new_info['content'] = $info['content'];
        $new_info['createtime'] = $info['createtime'];
        $this->success('获取成功！', $new_info);
    }

    /**
     * 获取辅导价格
     * @return void
     */
    public function getPriceRules()
    {
        $list = TutoringPriceRules::where(['status' => '1'])->field('id,duration,price,createtime')->select();
        $this->success('获取成功！', $list);
    }

    public function getjiaocheng()
    {
        $id = $this->request->param('id');
        $list = Db::table('jy_content_str')->where(['id' => $id])->find();
        $this->success('获取成功！', $list);
    }

    public function getAgreement()
    {
        $id = $this->request->param('id');
        $list = Db::table('jy_shopro_data_richtext')->where(['id' => $id])->find();
        $this->success('获取成功！', $list);
    }
}
